<template>
    <div class="score-overview">
      <div class="rank-change anchor-offset" id="fractional-distribution">
         <h3 class="header-with-select" style="margin-top:0;">年级各班级知识点得分率</h3>
         <el-table
          :data="gradescoreratelist"
          border 
          stripe
           :height="gradescoreratelist.length > 5 ? '504px' : undefined"
          :header-cell-style="{ background: '#e8f0fa', color: '#2A303B', fontWeight: '500' }"
          class="custom-table"
          tooltip-effect="dark"
          style="width: 100%"
        >
          <!-- 知识点名称列 -->
          <el-table-column
            prop="knowledgeName"
            label="知识点名称"
            fixed="left"
          />
          <!-- 年级平均得分率 -->
          <el-table-column
            label="年级"
            align="center"
          >
            <template #default="{ row }">
              {{ getScoreRate1(row, '年级') }}
            </template>
          </el-table-column>
          
          <!-- 动态生成各班级列 -->
          <el-table-column
            v-for="className in classNames1"
            :key="className"
            :label="className+'班'"
            align="center"
          >
            <template #default="{ row }">
              {{ getScoreRate1(row, className) }}
            </template>
          </el-table-column>
        </el-table>
        <!-- <el-table :data="rankChangeData" border v-loading="loadingRankChange"
        stripe
        :header-cell-style="{ background: '#e8f0fa', color: '#2A303B',fontWeight:'500' }"
        class="custom-table"
        tooltip-effect="dark"
        style="width: 100%">
          <el-table-column prop="name" label="知识点" align="center"/>
          <el-table-column prop="name" label="年级" align="center"/>
          <el-table-column prop="name" label="1班" align="center"/>
          <el-table-column prop="name" label="2班" align="center"/>
        </el-table> -->
      </div>
      <div class="rank-change anchor-offset" id="Two-point-five-rate">
         <h3 class="header-with-select">年级各科高频错题</h3>
         <el-table 
          :data="highfrequencyincorrectquestionslist" 
          border 
          stripe
          :height="highfrequencyincorrectquestionslist.length > 5 ? '504px' : undefined"
          :header-cell-style="{ background: '#e8f0fa', color: '#2A303B', fontWeight: '500' }"
          class="custom-table"
          tooltip-effect="dark"
          style="width: 100%">
          <!-- 固定列 -->
          <el-table-column prop="questionNum" label="题号" align="center" width="300">
            <template slot-scope="scope">
                {{ scope.row.examName }}-{{ scope.row.questionNum }}
            </template>
          </el-table-column>
          <el-table-column prop="questionTypeName" label="题型" align="center" width="120" />
          <el-table-column prop="knowledgeList" label="知识点" align="left" min-width="200">
            <template #default="scope">
                <span v-if="scope.row.knowledgeList === '待补充'" class="pending-data">
                      {{ scope.row.knowledgeList }}
                    </span>
                <div class="expandable-cell" style="display: flex; flex-wrap: wrap;" v-else>
                  <div style="padding-right: 10px;">
                    <!-- 显示内容部分 -->
                    <template v-if="scope.row.knowledgeList">
                      <!-- 展开状态下显示全部内容 -->
                      <span v-if="scope.row.expanded">
                        <span v-for="(item, index) in scope.row.knowledgeList.split('、')" :key="index">
                          {{ item }}<em v-if="index < scope.row.knowledgeList.split('、').length - 1">、</em>
                        </span>
                      </span>
                      
                      <!-- 收起状态下只显示前3条 -->
                      <span v-else>
                        <span v-for="(item, index) in scope.row.knowledgeList.split('、').slice(0, 3)" :key="index">
                          {{ item }}<em v-if="index < Math.min(3, scope.row.knowledgeList.split('、').length) - 1">、</em>
                        </span>
                        <i v-if="scope.row.knowledgeList.split('、').length > 3">...</i>
                      </span>
                       <a href="javascript:;" @click="toggleExpand(scope.row)" style="margin-left: 5px; color: #1890ff;"v-if="scope.row.knowledgeList.split('、').length > 3">
                        {{ scope.row.expanded ? '收起' : '展开' }}
                      </a>
                    </template>
                    <!-- <el-button
                    v-if="scope.row.knowledgeList.split('、').length > 3"
                    type="text"
                    size="mini"
                    @click="toggleExpand(scope.row)"
                    >
                    {{ scope.row.expanded ? '收起' : '展开' }}
                    </el-button> -->
                  </div>
                </div>
              </template>
          </el-table-column>
          <el-table-column 
            v-for="className in classNames" 
            :key="className"
            :label="`${className}班得分率`" 
            align="center"
            width="120">
            <template #default="{ row }">
              {{ getClassScoreRate(row, className) || '--' }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </template>
  <script>
  import { Gradescorerate,GradeHighfrequencyincorrectquestions} from '@/api/grade'
  
  export default {
    name: 'ScoreOverview',
    data() {
      return {
        subjectId:0,
        gradeId:0,
        classIds:[],
        startTime:'',
        endTime:'',
        gradescoreratelist:[],
        highfrequencyincorrectquestionslist:[],
        classNames: [] ,// 动态班级列表
        classNames1: []
      }
    },
  
    methods: {
      toggleExpand(row) {
        this.$set(row, 'expanded', !row.expanded);
      },
      // 年级各班级知识点得分率
      async gradescorerateateapi() {
        // console.info('this.gradeId',this.gradeId)
        // return false
        try {
          const res = await Gradescorerate(
            Number(this.subjectId),
            Number(this.gradeId), 
            String(this.classIds),
            String(this.startTime),
            String(this.endTime)
          )
          console.log('res 是否是 Promise:', res); // 应该是 false
          if (res.code === 200) {
            this.gradescoreratelist = res.data
            this.extractClassNames1();
          } else {
            throw new Error(res.message)
          }
        } catch (error) {
          console.error('加载成绩概览失败:', error)
          throw error  // 向上传递错误，让 loadData 统一处理
        }
      },
      //年级各班高频错题
      async gradeHighfrequencyincorrectquestionsapi() {
        // console.info('this.gradeId',this.gradeId)
          // return false
          try {
            const res = await GradeHighfrequencyincorrectquestions(
              Number(this.subjectId),
              Number(this.gradeId), 
              String(this.classIds),
              String(this.startTime),
              String(this.endTime)
            )
            console.log('res 是否是 Promise:', res); // 应该是 false
            if (res.code === 200) {
              this.highfrequencyincorrectquestionslist = res.data
              this.extractClassNames();
              // this.highfrequencyincorrectquestionslist = res.data.flatMap(item => {
              //   return item.classScoreRateMaps.map(rate => ({
              //     ...rate,
              //     questionTypeName: item.questionTypeName,
              //     questionId: item.questionId,
              //     examName: item.examName,
              //     questionNun: item.questionNun,
              //     knowledgeList: item.knowledgeList
              //   }));
              // });
              // console.info('ddddd',this.highfrequencyincorrectquestionslist)
            } else {
              throw new Error(res.message)
            }
          } catch (error) {
            console.error('加载成绩概览失败:', error)
            throw error  // 向上传递错误，让 loadData 统一处理
          }
        },
        // 提取所有班级名称
      extractClassNames() {
        const classSet = new Set();
        this.highfrequencyincorrectquestionslist.forEach(item => {
          item.classScoreRateMaps.forEach(rate => {
            classSet.add(rate.className);
          });
        });
        this.classNames = Array.from(classSet).sort();
      },
      
      // 获取指定班级的得分率
      getClassScoreRate(row, className) {
        const rate = row.classScoreRateMaps.find(item => item.className === className);
        return rate?.scoreRate;
      },
      extractClassNames1() {
        const classSet = new Set();
        this.gradescoreratelist.forEach(item => {
          item.knowLedgeScoreRateList.forEach(rate => {
            if (rate.groupName !== '年级') {
              classSet.add(rate.groupName);
            }
          });
        });
        this.classNames1 = Array.from(classSet).sort();
      },
      
      // 获取指定组的得分率
      getScoreRate1(row, groupName) {
        const rate = row.knowLedgeScoreRateList.find(
          item => item.groupName === groupName
        );
        return rate ? rate.knowledgeScoreRate : '--';
      },
    },
  
    mounted() {
      this.subjectId = Number(this.$route.query.subjectid) || 0
      this.gradeId = Number(this.$route.query.gradeid) || 0
      // this.classIds = (this.$route.query.classids || '').split(',').map(Number)
      this.classIds = this.$route.query.classids || ''
      this.startTime = this.$route.query.startTime || ''
      this.endTime = this.$route.query.endTime || ''
      this.gradescorerateateapi()
      this.gradeHighfrequencyincorrectquestionsapi()
      
    },
  }
  </script>
  
  <style scoped>
  .score-overview{
      background: #FFFFFF;
      box-shadow: 0 12px 16px 0 #5572921a;
      border-radius:10px;
      padding:24px;
  }
  .query-section {
    background: #fff;
    padding: 20px;
    border-radius: 4px;
    margin-bottom: 20px;
  }
  
  .query-form {
    display: flex;
    align-items: center;
  }
  
  .overview-section,
  .score-details,
  .score-analysis,
  .rank-change,
  .error-questions {
    background: #fff;
    border-radius: 4px;
  }
  
  .overview-content {
      box-sizing: border-box;
    background: #295cff0a;
    border: 1px solid #295cff33;
    border-radius: 10px;
    padding:18px 24px 0;
    font-size:14px;
  }
  
  .submit-info {
    margin-bottom: 16px;
    line-height: 1.8;
    color:#8E96A4
  }
  .submit-info span{
      color:#295CFF
  }
  .submit-info i{
      color:#5B6371;
      font-style: normal;
  }
  .submit-info b{
      font-style:normal;
      font-weight: normal;
  }
  .class-info {
    margin-top: 8px;
    text-indent: 2em;
    line-height: 1.8;
  }
  .score-row {
    display: flex;
    gap: 16px;
    justify-content: center;
  }
  .score-item {
    min-width: 40px;
    text-align: center;
  }
  .question-numbers {
    display: flex;
    gap: 16px;
    justify-content: center;
    margin-top: 8px;
    font-size: 12px;
  }
  .question-numbers span {
    min-width: 40px;
    text-align: center;
  }
  .rank-change {
    background: #fff;
    border-radius: 4px;
  }
  .change-info {
    display: flex;
    gap: 8px;
    justify-content: center;
  }
  .change-info .el-tag {
    min-width: 80px;
  }
  .error-questions {
    background: #fff;
    border-radius: 4px;
  }
  .el-tag {
    width: 80px;
    text-align: center;
  }
  .analysis-content {
    margin-top: 16px;
    line-height: 1.8;
  }
  .header-with-select{
      font-size:16px;
      color:#2A303B;
      margin-bottom:14px;
      margin-top:24px;
  }
  .custom-table {
    width: 100%;
    border: 1px solid rgba(216,228,240,1);
    border-radius:10px;
    border-right: none;
    border-bottom:none;
  }
  
  /* 自定义表格内部元素的样式 */
  .custom-table >>> .el-table__header-wrapper th {
    background-color: rgb(232, 240, 250);
    height:42px;
    padding:0;
    text-align: center;
    font-weight:normal
  }
  .custom-table >>> .el-table__row td {
    height:42px;
    padding:0;
    text-align: center;
    border-bottom:none;
    border-right:solid 1px rgba(216,228,240,1);
  }
  .el-table .warning-row {
      background: #ffffff;
   }
  .el-table .success-row {
      background: #D8E4F0;
  }
  .rank-change >>> .el-table .el-table__cell{
    padding:9px 0;
  }
  .anchor-offset {
    scroll-margin-top: 50px;
  }
  </style> 